<template>
  <el-dialog
    :title="dialogTitle"
    :width="700"
    :append-to-body="false"
    @close="handleClose"
    custom-class="center-detail"
    v-bind="$attrs"
  >
    <div class="create-share-wrap">
      <div class="row-title">发布</div>
      <div class="row-wrap release-wrap">
        <div class="el-switch-wrap" @click="onRelease">
          <el-switch v-model="release" inline-prompt active-text="开启" inactive-text="关闭" />
        </div>
        已{{ release ? '开启' : '关闭' }}发布
      </div>
      <div v-if="release" class="row-title">分享链接</div>
      <div v-if="release" class="row-wrap">
        <el-button class="create-btn" type="primary" @click="insertLink">创建链接</el-button>
      </div>
      <div v-if="release && shareList.length" class="share-list">
        <div class="share-list-item" v-for="(list, idx) in shareList" :key="idx">
          <div class="share-header">
            <div class="share-type">
              {{ ShareType[list.shareType] && ShareType[list.shareType].value }}
            </div>
            <div>有效时间：{{ list.expirationTimeName }}</div>
          </div>
          <div class="share-content">
            <el-input v-model="list.shareUrl" disabled></el-input>
            <el-button
              v-if="list.shareStatus === 0 && list.expirationTimeState !== 3"
              @click="onCancel(list)"
              >取消分享</el-button
            >
            <el-button
              v-if="list.shareStatus === 0 && list.expirationTimeState !== 3"
              type="primary"
              @click="onCopy(list)"
              >复制链接</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 分享设置 -->
  <ShareSetting
    v-if="shareSettingDialogVisible"
    v-model="shareSettingDialogVisible"
    :scene="props.scene"
    @close-handle="shareSettingCloseHandle"
  />
</template>

<script setup lang="ts">
import ShareSetting from './share-setting.vue';
import { confirmAgain, calcExpirationTime, copyText } from '@/utils';
import { useRequest } from '@jl/common/composable';
import {
  getSceneShareList,
  cancelSceneShare,
  toggleReleaseState,
  getActLmState,
} from '@/api/scene';
import withBase from '@jl/common/src/utils/path';
import {
  ShareType,
  SCENE_LOGICMARK_DELETE,
  SCENE_LOGICMARK_START,
  SCENE_LOGICMARK_STOP,
} from '@/views/enum/scene';
import { debounce } from 'lodash';

import { messageUtil } from '@jl/element-plus/utils';

defineOptions({
  name: 'CreateShare',
});

interface IProps {
  scene: API.Scene.SceneListItem | null;
}

const props = withDefaults(defineProps<IProps>(), {
  scene: null,
});

const emits = defineEmits(['closeHandle', 'update']);

const { run: lmRun, data: lmData } = useRequest<any, any>(
  getActLmState,
  [],
  {},
  {
    onSuccess: operateData,
  }
);
const { run: shareListRun, data: shareListData } = useRequest<any, any>(
  getSceneShareList,
  [{ list: [], total: 0 }],
  {},
  {
    onSuccess(res: any) {
      if (res[0].list.length) {
        const resourceCodeMap = {} as any;
        res[0].list.forEach((v: any) => {
          if (!resourceCodeMap[v.resourceCode]) {
            resourceCodeMap[v.resourceCode] = v.resourceCode;
          }
        });
        const fData = new FormData();
        fData.set('actIds', Object.keys(resourceCodeMap).join(';'));
        lmRun({
          data: fData,
        });
      }
    },
  }
);

const shareSettingDialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('场景发布分享');
const release = ref<boolean>(false);
const shareList = ref<any>([]);

onMounted(() => {
  if (!props.scene) return;
  release.value = props.scene.releState;
  shareListRun({
    data: {
      index: 1,
      pageSize: 10000,
      resourceCode: props.scene!.activityId,
    },
  });
});

function handleClose() {
  emits('closeHandle', false);
}

function shareSettingCloseHandle(flag = false) {
  shareSettingDialogVisible.value = false;
  if (flag) {
    shareListRun({
      data: {
        index: 1,
        pageSize: 10000,
        resourceCode: props.scene!.activityId,
      },
    });
  }
}

const onRelease = debounce(
  async () => {
    if (!release.value) {
      const fData = new FormData();
      fData.set('activityId', props.scene?.activityId);
      fData.set('releState', true);
      toggleReleaseState({
        data: fData,
      }).then(() => {
        release.value = true;
        emits('update');
      });
      return;
    }
    const result = await confirmAgain('确认取消发布？', '关闭后，之前生成的分享链接将失效');
    if (result) {
      const fData = new FormData();
      fData.set('activityId', props.scene?.activityId);
      fData.set('releState', false);
      toggleReleaseState({
        data: fData,
      }).then(() => {
        release.value = false;
        emits('update');
        // 将所有关联分享取消
        if (!shareList.value.length) return;
        cancelSceneShare({ data: { ids: shareList.value.map((item: any) => item.id) } }).then(
          () => {
            shareListRun({
              data: {
                index: 1,
                pageSize: 10000,
                resourceCode: props.scene!.activityId,
              },
            });
          }
        );
      });
    }
  },
  400,
  {
    leading: true,
    trailing: false,
  }
);

async function onCancel(item: API.Scene.IShareListItem) {
  const flag = await confirmAgain('确认取消该场景分享？', '该操作不可逆，取消后分享链接将失效。');
  if (!flag) return;
  cancelSceneShare({ data: { ids: [item.id] } }).then(() => {
    shareListRun({
      data: {
        index: 1,
        pageSize: 10000,
        resourceCode: props.scene!.activityId,
      },
    });
  });
}

function onCopy(row: API.Scene.IShareListItem) {
  let str = `${location.origin}${withBase()}share/scene/${row.shareCode}`;
  if (row.shareType === 'encrypt') {
    str = '链接：' + str + ` 密码：${row.accessPassword}`;
  }
  copyText(str);
}

function insertLink() {
  if (props.scene!.logicMark !== SCENE_LOGICMARK_START) {
    messageUtil.warning('该场景关联项目停用，无法创建分享链接');
    return;
  }
  shareSettingDialogVisible.value = true;
}

function operateData() {
  const logicMarkMap = {} as any;
  lmData.value.forEach((v: any) => {
    logicMarkMap[v.actId] = v.logicMarkState;
  });
  for (const list of shareListData.value[0].list) {
    const expirationTimeResult = calcExpirationTime(list.expirationTime);
    const logicMark = logicMarkMap[list.resourceCode];
    if (logicMark !== undefined && logicMark !== SCENE_LOGICMARK_START) {
      list.shareStatus = 1;
    }
    list.expirationTimeName = list.shareStatus === 1 ? '已过期' : expirationTimeResult.name;
    list.expirationTimeState = list.shareStatus === 1 ? 3 : expirationTimeResult.code;
    list.shareUrl = `${location.origin}${withBase()}share/scene/${list.shareCode}`;
  }
  shareList.value = shareListData.value[0].list;
}
</script>

<style lang="less" scoped>
.create-share-wrap {
  padding-left: 10px;
}
.row-title {
  font-size: 16px;
  font-weight: 500;
  color: #585858;
  margin-bottom: 10px;
}
.row-wrap {
  display: flex;
  color: #161616;
  margin-bottom: 20px;
  padding-left: 10px;
  .el-switch {
    margin-right: 8px;
  }
  .create-btn {
    width: 88px;
  }
  &.release-wrap {
    align-items: center;
    .el-switch-wrap {
      cursor: pointer;
      .el-switch {
        pointer-events: none;
      }
    }
  }
  &:last-child {
    margin-bottom: 0px;
  }
}
.share-list {
  border-top: 1px solid #e8e8e8;
  padding: 18px 0 0 0;
  margin-left: 10px;
  &-item {
    margin-bottom: 20px;
    .share-header {
      display: flex;
      margin-bottom: 11px;
      color: #161616;
      .share-type {
        margin-right: 20px;
      }
    }
    .share-content {
      display: flex;
      align-items: center;

      .el-button:first-of-type {
        border-color: #0560fd;
      }

      .el-input {
        --el-input-height: 44px;
        --el-disabled-bg-color: #fff;
        --el-disabled-border-color: #e8e8e8;
        width: 444px;
        margin-right: 10px;
      }
    }
    &:last-child {
      margin-bottom: 0px;
    }
  }
}
</style>
